package service

import (
	"context"

	"google.golang.org/protobuf/types/known/wrapperspb"

	pb "gitee.com/shuokeyun/merchant-service/api/v1"
	"gitee.com/shuokeyun/merchant-service/internal/domain"
)

// UserAuthService .
type UserAuthService struct {
	pb.UnimplementedUserAuthServer
	userAuth domain.UserAuthUsecase
}

// NewUserAuthServer .
func NewUserAuthServer(userAuth domain.UserAuthUsecase) pb.UserAuthServer {
	return &UserAuthService{
		userAuth: userAuth,
	}
}

// Login .
func (s *UserAuthService) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginReply, error) {
	auth, err := s.userAuth.Login(ctx, req.GetMobile(), req.GetPassword(), req.GetAppId())
	if err != nil {
		return nil, err
	}
	return &pb.LoginReply{
		Id:         auth.Id,
		MerchantId: auth.MerchantId,
		Mobile:     auth.Mobile,
		Username:   auth.Username,
		RealName:   auth.RealName,
		Role:       auth.Role,
		ExpiredAt:  auth.ExpiredAt,
		Token:      auth.Token,
	}, nil
}

// Logout .
func (s *UserAuthService) Logout(ctx context.Context, req *pb.LogoutRequest) (*wrapperspb.BoolValue, error) {
	err := s.userAuth.Logout(ctx, req.GetId(), req.GetAppId())
	if err != nil {
		return nil, err
	}
	return &wrapperspb.BoolValue{
		Value: true,
	}, nil
}

// CheckLogin .
func (s *UserAuthService) CheckLogin(ctx context.Context, req *pb.CheckLoginRequest) (*pb.CheckLoginReply, error) {
	auth, err := s.userAuth.CheckLogin(ctx, req.GetToken(), req.GetAppId())
	if err != nil {
		return nil, err
	}
	return &pb.CheckLoginReply{
		Id:         auth.Id,
		MerchantId: auth.MerchantId,
		Mobile:     auth.Mobile,
		Username:   auth.Username,
		RealName:   auth.RealName,
		Role:       auth.Role,
		ExpiredAt:  auth.ExpiredAt,
		Token:      auth.Token,
	}, nil
}
